﻿using MyMVC.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;

namespace MyMVC.DAL
{
   public class DepartmentService
    {
        /// <summary>
        /// 查询所有部门信息
        /// </summary>
        /// <returns></returns>
        public List<Department> getd() {
            string sql = "select * from Department";
            List<Department> ld = new List<Department>();
            SqlDataReader dr = DBHelper.Reader(sql);
            while (dr.Read()) {
                Department d = loaddepartment(dr);
                ld.Add(d);
            }
            dr.Close();
            return ld;
        }

        /// <summary>
        /// 根据id查询部门信息
        /// </summary>
        /// <param name="depid"></param>
        /// <returns></returns>
        public Department GetDepartmentID(int depid) {
            string sql = "select * from Department where DepId=@id";
            SqlDataReader sd = DBHelper.Reader(sql,sps:new SqlParameter("@id", depid));
            Department department = null;
            while (sd.Read()) {
                department = loaddepartment(sd);
            }
            sd.Close();
            return department;
        }

        /// <summary>
        /// 遍历部门信息
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private Department loaddepartment(SqlDataReader dr) {
            Department dep = new Department();
            dep.DepId = Convert.ToInt32(dr[0]);
            dep.DepName = dr[1].ToString();
            return dep;
        }

        /// <summary>
        /// 添加部门信息
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        public int addpar(Department d) {
            string sql = "insert into Department values(@DepName)";
            SqlParameter[] sp = new SqlParameter[]
            {
                new SqlParameter("@DepName",d.DepName)
            };
            return DBHelper.NonQuery(sql, sps: sp);
        }
    }
}
